﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text.RegularExpressions;
using eDoc.BO;
using System.IO;

namespace eDoc
{
    public partial class plist : System.Web.UI.Page
    {
        private string ak = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["ak"] != null && Request.QueryString["ak"].ToString() != "")
            {
                ak = Request.QueryString["ak"].ToString();
            }
            if (!IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
//            <a href='itms-services://?action=download-manifest&url=http://192.168.0.101:9897/File/FileInfo/AllTest/AllTest.plist'><img src="/images/apple-02.png" title="Tải ứng dụng" /></a>
            if (ak != "")
            {
                DataTable dt = new DataTable();
                dt = BO.Data.Select_AppPlist_by_AppKey(ak);
                string appPlistContent = "";
                if (dt != null && dt.Rows.Count > 0)
                {
                    ltrAppName.Text = dt.Rows[0]["AppName"].ToString();
                    ltrAppVersion.Text = dt.Rows[0]["AppVersion"].ToString();
                    ltrBundleIdentifier.Text = dt.Rows[0]["AppBundleIdentifier"].ToString();
                    if (dt.Rows[0]["AppDeviceFamily"].ToString()=="1")
                    {
                        ltrAppFamilyDevice.Text = "iPad";
                    }
                    else
                    {
                        ltrAppFamilyDevice.Text = "iPhone";
                    }
                    
                    ltrHDH.Text = dt.Rows[0]["AppMinimumOSVersion"].ToString();
                    string randomStr = System.Common.RandomStrings.RandomString(10);                    
                    
                    string[] arr = dt.Rows[0]["AppPlistPath"].ToString().Split("/".ToCharArray());
                    string plistName = "", pathSave="";
                    if(arr.Length>0)
                    {
                        plistName = arr[arr.Length-1].ToString();
                    }
                    
                    pathSave = dt.Rows[0]["AppPlistPath"].ToString().Replace(plistName,"");

                    string newPlist = string.Empty;

                    double os = ReturnOS();                   

                    if (os < 7)
                    {
                        appPlistContent = string.Format(dt.Rows[0]["AppPlistContent"].ToString(), randomStr);
                        newPlist = SavePlist(pathSave, plistName.Replace(".plist", "") + randomStr + ".plist", appPlistContent);                    
                        ltrPlist.Text = "<a href='itms-services://?action=download-manifest&url=" + BO.Common.UrlInstall + newPlist + "'> <img src='/images/apple-02.png' title='Tải ứng dụng' /></a>";
                    }
                    else if(os<9 && os>=7)
                    {
                        appPlistContent = string.Format(dt.Rows[0]["AppPlistContent"].ToString(), randomStr);
                        newPlist = SavePlist(pathSave, plistName.Replace(".plist", "") + randomStr + ".plist", appPlistContent);                    
                        ltrPlist.Text = "<a href='itms-services://?action=download-manifest&url=" + BO.Common.UrlInstall.Replace("http://", "https://") + newPlist + "'> <img src='/images/apple-02.png' title='Tải ứng dụng' /></a>";
                    }
                    else
                    {
                        appPlistContent = string.Format(dt.Rows[0]["AppPlistContent"].ToString(), string.Empty);
                        newPlist = SavePlist(pathSave, plistName, appPlistContent);
                        ltrPlist.Text = "<a href='itms-services://?action=download-manifest&url=" + BO.Common.UrlInstall.Replace("http://", "https://") + newPlist + "'> <img src='/images/apple-02.png' title='Tải ứng dụng' /></a>";
                    }

                    ltrAppSize.Text = BO.Common.ReturnAppSize(dt.Rows[0]["AppSize"].ToString());
                    ltrBuildTime.Text = Convert.ToDateTime(dt.Rows[0]["AppPListDateCreated"]).ToString("dd/MM/yyyy HH:mm");
                    ltrAppDisplayName.Text = dt.Rows[0]["AppDisplayName"].ToString();
                    ltrAppDesc.Text = dt.Rows[0]["AppDesc"].ToString();
                }
            }
            else
            {

            }
        }


        private string SavePlist(string pathSave, string fileName ,string plistContent)
        {
            string urlPlist = pathSave + fileName;
            string folderSave = Server.MapPath(pathSave);
            if (!Directory.Exists(folderSave))
                Directory.CreateDirectory(folderSave);

            FileStream fileStream = new FileStream(folderSave + "\\" + fileName, FileMode.Create, FileAccess.ReadWrite);
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(plistContent);
            fileStream.Write(buffer, 0, buffer.Length);
            fileStream.Close();

            return urlPlist;
        }


        private string reg = @"(\d+)_(\d+)";
        private Double ReturnOS()
        {
            string value = "0";
            string useragent = HttpContext.Current.Request.UserAgent;
            Match match = Regex.Match(useragent, reg);

            if (match.Success)
            {
                value = match.Groups[0].Value.ToString().Replace("_", ".");
            }

            return Convert.ToDouble(value);
        }
    }
}